<?php
namespace App\Services;

use App\Core\Log;
use App\Factory\WechatFactory;
use App\Traits\ReturnTrait;
use GuzzleHttp\Client;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Str;

class MiniProgramService
{
    use ReturnTrait;
    /**
     * @Inject
     * @var WechatFactory
     */
    private $wechat_factory;
    public $app;

    public function __construct()
    {
        $this->app = $this->wechat_factory->create();
    }

    public function createQrcode($params){
        $http = new Client();
        $access_token = $this->getToken();
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $params['is_hyaline'] = false;
        $response = $http->post($url, [
            'json' => $params
        ]);
        $res = $response->getBody();
        //Log::get('api')->info('生成二维码数据'.$res);
        $imgdata = base64_encode($res);
        $path = 'uploads/miniqrcode/'.date('Ym').'/'.date('d');
        $a_path = BASE_PATH.'/public/'.$path;
        $filename = md5(time().Str::random(6)).'.png';
        is_dir($a_path) or mkdir($a_path, 0777,true);
        $r = file_put_contents($a_path.'/'.$filename, base64_decode($imgdata));
        if (!$r) {
            return $this->error('二维码生成失败');
        }else{
            return $this->success([
                'qrcode' => $path.'/'.$filename
            ]);
        }
    }

    private function getToken(){
        $accessToken = $this->app->access_token;
        $token = $accessToken->getToken();
        $access_token = $token['access_token'];
        return $access_token;
    }
}